package com.rxyb.toolize;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.util.Random;
import java.util.UUID;

/**
 * 处理类
 *
 * @author duyh
 * @date 2020-05-14
 */
public class VO {

    /**
     * 创建流水号 @Title radomTransNo @return String @throws
     */
    public static String radomTransNo() {
        return radomString(24);
    }

    /**
     * 获取固定长度的随机号，包含数字和字母
     *
     * @param length 不超过32
     * @return
     */
    public static String radomString(int length) {
        if (length > 32) {
            return null;
        }
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, length);
    }

    /**
     * 创建固定长度的编号
     *
     * @param length 不超过32
     * @return
     */
    public static String radomNumberStr(int length) {
        if (length > 32) {
            return null;
        }
        int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        Random rand = new Random();
        for (int i = 40; i > 1; i--) {
            int index = rand.nextInt(i);
            int tmp = array[index];
            array[index] = array[i - 1];
            array[i - 1] = tmp;
        }
        String result = "";
        for (int i = 0; i < length; i++) {
            result += array[i];
        }
        return result;
    }

    /**
     * 是否为数字
     */
    public static boolean isNumber(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 是否为空或NULL
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        return StringUtils.isBlank(str);
    }

    /**
     * 是否不为空或NULL
     *
     * @param str
     * @return
     */
    public static boolean isNotBlank(String str) {
        return StringUtils.isNotBlank(str);
    }

    /**
     * 是否相等，自动验证NULL
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean isEquals(String str1, String str2) {
        return StringUtils.equals(str1, str2);
    }

    /**
     * 求优雅输出
     *
     * @param json
     * @return json
     */
    public static String format(String json) {
        ObjectMapper mapper = new ObjectMapper();
        Object obj;
        try {
            obj = mapper.readValue(json, Object.class);
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
        }
        return json;
    }

}